import com.sun.deploy.net.proxy.ProxyUnavailableException;

/**
 * Created with IntelliJ IDEA.
 * Description:synchronized修饰代码块
 * User: lenovo
 * Date: 2022-09-22
 * Time: 20:41
 */
class Counter1{
    int counter = 0;
    public  void increase(){
       synchronized (this){//synchronized可以修饰任何对象 ()里面可以放任何对象,这里填写this表示当前对象,
           // 即哪个对象调用increase就给哪个对象上锁,这里是counter调用
            counter++;
        }

    }

}
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        Counter1 counter1 = new Counter1();
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                counter1.increase();
            }
        },"这是线程1");

        Thread thread2 = new Thread(()->{

            for (int i = 0; i < 5000; i++) {
                counter1.increase();
            }
        },"这是线程2");

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
        System.out.println(counter1.counter);
    }
}
